package com.cws.project.cws.resitscore.controller;

import java.util.List;
import java.util.stream.Collectors;

import com.cws.common.utils.StringUtils;
import com.cws.common.utils.file.FileUtils;
import com.cws.common.utils.poi.ExcelUtil;
import com.cws.framework.aspectj.lang.annotation.Log;
import com.cws.framework.aspectj.lang.enums.BusinessType;
import com.cws.framework.web.controller.BaseController;
import com.cws.framework.web.domain.AjaxResult;
import com.cws.framework.web.page.TableDataInfo;
import com.cws.project.cws.clazz.domain.ClazzUser;
import com.cws.project.cws.clazz.service.IClazzUserService;
import com.cws.project.cws.resit.domain.CourseResit;
import com.cws.project.cws.resit.service.ICourseResitService;
import com.cws.project.system.user.domain.User;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.cws.project.cws.resitscore.domain.CourseResitScore;
import com.cws.project.cws.resitscore.service.ICourseResitScoreService;

import javax.servlet.http.HttpServletResponse;

/**
 * 补考得分Controller
 *
 * @author xyl
 * @date 2022-03-26
 */
@Controller
@RequestMapping("/cws/resitscore")
public class CourseResitScoreController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(CourseResitScoreController.class);

    private String prefix = "cws/resitscore";

    @Autowired
    private ICourseResitScoreService courseResitScoreService;
    @Autowired
    private ICourseResitService courseResitService;
    @Autowired
    private IClazzUserService clazzUserService;

    @RequiresPermissions("cws:resitscore:view")
    @GetMapping()
    public String resitscore() {
        return prefix + "/resitscore";
    }

    /**
     * 查询补考得分列表
     */
    @RequiresPermissions("cws:resitscore:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(CourseResitScore courseResitScore) {

        User sysUser = getSysUser();
        //todo 学生只能看见自己的 ，但是暂时还没学生的权限

        //辅导员 查看自己班的
        if(sysUser.isInstructor()){
            ClazzUser clazzUser = new ClazzUser();
            clazzUser.setUserId(sysUser.getUserId());
            courseResitScore.setClazzIds(clazzUserService.selectClazzUserList(clazzUser).stream().map(ClazzUser::getClazzId).collect(Collectors.toList()));
        }
        //教师
        if(sysUser.isTeacher()){
            courseResitScore.setTeacherId(sysUser.getUserId());
        }
        startPage();
        List<CourseResitScore> list = courseResitScoreService.selectCourseResitScoreList(courseResitScore);
        return getDataTable(list);
    }

    /**
     * 导出补考得分列表
     */
    @RequiresPermissions("cws:resitscore:export")
    @Log(title = "补考得分", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(CourseResitScore courseResitScore) {
        List<CourseResitScore> list = courseResitScoreService.selectCourseResitScoreList(courseResitScore);
        ExcelUtil<CourseResitScore> util = new ExcelUtil<CourseResitScore>(CourseResitScore.class);
        return util.exportExcel(list, "resitscore");
    }

    @GetMapping("/download/{resitScoreId}")
    public void download(@PathVariable("resitScoreId") Long resitScoreId, HttpServletResponse response) throws Exception {
        CourseResitScore courseResitScore = courseResitScoreService.selectCourseResitScoreById(resitScoreId);
        if(ObjectUtils.isEmpty(courseResitScore)){
            throw new Exception("非法请求！");
        }
        try {
            String filePath = courseResitScore.getDocUrl().replace("http://localhost:8080/profile/", "D:/cws/uploadPath/");
            String fix = filePath.substring(filePath.lastIndexOf("."));
            String realFileName = courseResitScore.getCourseName() + "-" + courseResitScore.getLoginName() + "-" + courseResitScore.getUserName() + fix;
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 新增补考得分
     */
    @GetMapping("/add/{resitId}")
    public String add(@PathVariable Long resitId,ModelMap mmap) {
        mmap.put("resitId",resitId);
        return prefix + "/add";
    }

    /**
     * 新增保存补考得分
     */
    @RequiresPermissions("cws:resit:submit")
    @Log(title = "补考得分", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(CourseResitScore courseResitScore) {
        if (courseResitScore.getResitId() == null) {
            return error("参数有误！");
        }
        //验证时效
        CourseResit resit = courseResitService.selectCourseResitById(courseResitScore.getResitId());
        if(StringUtils.equals(resit.getIsEnd(),"已结束")){
            return error("已结束，不可提交！");
        }
        User sysUser = getSysUser();
        //验证不能重复提交
        CourseResitScore crs = courseResitScoreService.selectCourseResitScoreByRepet(courseResitScore.getResitId(),sysUser.getUserId());
        if(crs != null && StringUtils.isNotBlank(crs.getDocUrl())){
            return error("不可重复提交！");
        }
        if(crs != null){
            courseResitScore.setResitId(crs.getResitId());
        }
        courseResitScore.setCreateBy(getLoginName());
        courseResitScore.setStudentId(getUserId());
        return toAjax(courseResitScoreService.insertCourseResitScore(courseResitScore));
    }

    /**
     * 修改补考得分
     */
    @GetMapping("/edit/{resitScoreId}")
    public String edit(@PathVariable("resitScoreId") Long resitScoreId, ModelMap mmap) {
        CourseResitScore courseResitScore = courseResitScoreService.selectCourseResitScoreById(resitScoreId);
        mmap.put("courseResitScore", courseResitScore);
        return prefix + "/edit";
    }

    /**
     * 修改保存补考得分
     */
    @RequiresPermissions("cws:resitscore:edit")
    @Log(title = "补考得分", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(CourseResitScore courseResitScore) {
        return toAjax(courseResitScoreService.updateCourseResitScore(courseResitScore));
    }

    /**
     * 删除补考得分
     */
    @RequiresPermissions("cws:resitscore:remove")
    @Log(title = "补考得分", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(courseResitScoreService.deleteCourseResitScoreByIds(ids));
    }
}
